package mainmodel

import (
	"sync"
	"web_server/model"
)

type VoidT struct{}
type SetInt64 map[int64]VoidT

var rolePerm map[int64]SetInt64 = make(map[int64]SetInt64)
var rolePermMut sync.RWMutex

func CheckRolePerm(role, perm int64) bool {
	rolePermMut.RLock()
	if v, ok := rolePerm[role]; ok {
		_, have := v[perm]
		rolePermMut.RUnlock()
		return have
	}
	rolePermMut.RUnlock()
	rolePermMut.Lock()
	defer rolePermMut.Unlock()
	if v, ok := rolePerm[role]; ok {
		_, have := v[perm]
		return have
	}
	permset := getRolePermSet(role)
	rolePerm[role] = permset
	_, have := permset[perm]
	return have

	// permset := getRolePermSet(role)
	// rolePerm[role] = permset
	// _, have := permset[perm]
	// return have
}

func ClearRolePerm() {
	rolePermMut.Lock()
	defer rolePermMut.Unlock()
	rolePerm = make(map[int64]SetInt64)
}

func getRolePermSet(role int64) (permset SetInt64) {
	permset = make(SetInt64)

	var permids []int64
	if err := model.DBSlaveRand().Select(&permids, "SELECT permission_id FROM t_base_role_permission WHERE role_id = ?", role); err != nil {
		panic(err)
	}
	for _, v := range permids {
		permset[v] = VoidT{}
	}
	return
}
